package com.iecm.listener;

import com.alibaba.fastjson.JSONObject;
import com.iecm.common.config.RabbitConfig;
import com.iecm.common.utils.RabbitUtil;
import com.iecm.common.utils.RedisUtil;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

@Component
public class WeatherListener {

    @Autowired
    private RabbitUtil rabbitUtil;

    @Autowired
    private RabbitConfig rabbitConfig;

    @Autowired
    private RedisUtil redisUtil;

    @RabbitHandler
    @RabbitListener(queues = "weather_queue")
    public void receiveWeather(Channel channel, Message message) throws IOException {
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        String messageId = message.getMessageProperties().getHeaders().get("spring_returned_message_correlation").toString();
        if(redisUtil.hasKey("message:"+messageId)){
            return;
        }
        redisUtil.set("message:"+messageId, messageId, 1000);
        URL url = new URL("http://api.weatherdt.com/common/?area=101120308&type=observe&key=5b442752f46cc6cd3c51ece9ae48e162");
        HttpURLConnection uRLConnection = (HttpURLConnection)url.openConnection();
        uRLConnection.setDoOutput(true);
        uRLConnection.connect();
        InputStream is = uRLConnection.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String respJson = "";
        String readLine = null;
        while((readLine =br.readLine()) != null){
            respJson +=readLine;
        }
        JSONObject jsonObject = JSONObject.parseObject(respJson).getJSONObject("observe").getJSONObject("101120308").getJSONObject("1001002");
        is.close();
        br.close();
        uRLConnection.disconnect();

        rabbitUtil.writeToServer(rabbitConfig.weatherResult().getName(), jsonObject);
    }
}
